import os
import sys
import threading
import time

import winsound
from PyQt5 import QtCore
from PyQt5.QtCore import QObject, pyqtSignal, QEventLoop, QTimer
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QTextEdit
from PyQt5.QtGui import QTextCursor, QFont
from selenium.common.exceptions import SessionNotCreatedException

'''
控制台输出定向到Qtextedit中
'''


class Stream(QObject):
    """Redirects console output to text widget."""
    newText = pyqtSignal(str)

    def write(self, text):
        self.newText.emit(str(text))

curWid = 800
curHei = 600
version = "V1.8.6"
class PyWindow(QMainWindow):
    """Main application window."""
    def __init__(self):
        super().__init__()
        #禁止最大化按钮
        QMainWindow.setWindowFlags(self,QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
        #禁止拉伸窗口大小
        QMainWindow.setFixedSize(self,curWid, curHei);
        self.initUI()
        # Custom output stream.
        sys.stdout = Stream(newText=self.onUpdateText)
        sys.stderr = Stream(newText=self.onUpdateText)
        btn = QPushButton("Close", self)
        btn.clicked.connect(self.closeEvent)
        p1 = threading.Thread(target=self.closeTipsWindow)
        p1.start()
        print("启动窗体成功！！")
    def closeTipsWindow(self):
        from DoctorAutomate import DoctorAutomate
        doctorAutomate = DoctorAutomate(version)
        # 报错三次则通知管理员
        index = 1
        while True:
            try:
                doctorAutomate.start()
            except Exception:
                index = index + 1
                if index < 4:
                    continue
                else:
                    try:
                        doctorAutomate.sendMessage("=============="+version+"=自动化程序报错，立即通知管理员=============",doctorAutomate.driver.page_source)
                        winsound.Beep(400, 900)
                        winsound.Beep(400, 900)
                        import traceback
                        traceback.print_exc()
                        break
                    except SessionNotCreatedException as e:
                        print("=================浏览器启动版本不对，请查看 更新的内容.txt===================="+version)
                        winsound.Beep(400, 900)
                        winsound.Beep(400, 900)
                        import traceback
                        traceback.print_exc()
                        break
                    except Exception:
                        doctorAutomate.log("=============="+version+"=自动化程序报错，立即通知管理员=============")
                        winsound.Beep(400, 900)
                        winsound.Beep(400, 900)
                        import traceback
                        traceback.print_exc()
                        break
    def onUpdateText(self, text):
        """Write console output to text widget."""
        cursor = self.process.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    def closeEvent(self, event):
        # sys.stdout = sys.__stdout__
        # 退出应用程序
        os.system('taskkill /F /IM chrome.exe')
        os._exit()
    def initUI(self):
    # Set window size and title, then show the window.
        desktop = QApplication.desktop()

        cen_x = (desktop.width() - curWid) / 2
        cen_y = (desktop.height() - curHei) / 2
        # Create the text output widget.
        self.process = QTextEdit(self, readOnly=True)
        self.process.setHtml("<font color='black' size='6'>欢迎使用！</font>")
        self.process.ensureCursorVisible()
        # self.process.setLineWrapColumnOrWidth(500)
        # self.process.setLineWrapMode(QTextEdit.FixedPixelWidth)
        self.process.setFixedWidth(curWid)
        self.process.setFixedHeight(curHei)
        self.process.setFontPointSize(100 )
        self.setGeometry(cen_x, cen_y, curWid,curHei )
        self.setWindowTitle('自动化插件'+version)
        self.show()
if __name__ == '__main__':
    # Run the application.
    app = QApplication(sys.argv)
    # app.aboutToQuit.connect(app.deleteLater)
    gui = PyWindow()
    sys.exit(app.exec_())
